import { login, editor, getUserInfo } from "@/api/user"
const state = {
    pass: "admin123",
    username: "",
    nickname: "",
    user_id: "",
    type: 1,
    phone: "",
    img: ""
}

const mutations = {
    SET_USERNAME(state, payload) {
        state.username = payload
    },
    SET_NICKNAME(state, payload) {
        state.nickname = payload
    },
    SET_USER_ID(state, payload) {
        state.user_id = payload
    },
    DEL_USER_ID(state) {
        state.user_id = ""
    },
    SET_TYPE(state, payload) {
        state.type = payload
    },
    SET_PHONE(state, payload) {
        state.phone = payload
    },
    SET_IMAGE(state, payload) {
        state.img = payload
    }
}

const actions = {
    async login({ commit }, userInfo) {
        let res = await login(userInfo);

        if (res.data.length) {
            commit("SET_USERNAME", res.data[0].username)
            commit("SET_NICKNAME", res.data[0].nickname)
            commit("SET_USER_ID", res.data[0].id)
            commit("SET_TYPE", res.data[0].type)
            return {
                code: 200,
                msg: "登录成功",
                data: res.data[0]
            }
        } else {
            return {
                code: 201,
                msg: "用户名或密码错误",
                data: {}
            }
        }
    },

    async editor({ commit }, userInfo) {
        let { id, phone, img, password } = userInfo
        try {
            let res = await editor(id, { phone, img, password })
            commit("SET_PHONE", res.data.phone)
            commit("SET_IMAGE", res.data.img)
            return res

        } catch (err) {

        }
    },
    async getUserInfo({ commit }, id) {

        try {
            let res = await getUserInfo(id)
            commit("SET_PHONE", res.data.phone)
            commit("SET_IMAGE", res.data.img)
            return res

        } catch (err) {

        }
    },
}
export default {
    state,
    mutations,
    actions
}